<template>
  <div>
    <h1>添加商品</h1>

    <label for="name">名称：</label>
    <input type="text" id="name" v-model="formData.name"><br><br>

    <label for="image">图片：</label>
    <input type="file" id="image" ref="imageInput"><br><br>

    <label for="price">价格：</label>
    <input type="number" id="price" v-model="formData.price"><br><br>


    <label for="content">内容：</label>
    <textarea id="content" v-model="formData.content"></textarea><br><br>


    <button type="submit" @click="addGoods">添加</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        name: '',
        price: '',
        content: ''
      }
    };
  },
  methods: {
    addGoods() {
      const formData = new FormData();
      // 添加其他表单字段的值到formData
      formData.append('name', this.formData.name);
      formData.append('price', this.formData.price);
      formData.append('content', this.formData.content);

      // 添加图片文件到formData
      const imageFile = this.$refs.imageInput.files[0];
      formData.append('image', imageFile);

      // 发送POST请求将商品数据发送到后端API
      this.$http.post('/goods/addgoods', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
          this.$toast(response.data.message)
          this.$router.go(-1)
      })
      .catch(error => {
        console.error('添加商品失败:', error);
      });
    }
  }
}
</script>
